package edu.pku.hawk.datasource;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import edu.pku.hawk.controller.util.Constants;

public class ConnectDB {
	private String dbName;
	private String url;
	private java.sql.Connection cn;
	private static ConnectDB dbConnection = null;

	private ConnectDB(String username, String password, String url, String dbName) {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			// String conStr = "jdbc:mysql://localhost:3306/demo"
			String conStr = "jdbc:mysql://" + url + "/" + dbName;
			System.out.print("Connecting to " + conStr + " ...");
			cn = DriverManager.getConnection(conStr, username, password);
			this.dbName = dbName;
			this.url = url;
			System.out.println("Down.");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	public static ConnectDB getDBConnection(String userName, String password, String dbURL, String dbName) {
		if (dbConnection == null) {
			dbConnection = new ConnectDB(userName, password, dbURL, dbName);
		} else {
			if (!dbConnection.url.equalsIgnoreCase(dbURL) && !dbConnection.dbName.equalsIgnoreCase(dbName)) {
				try {
					dbConnection.close();
				} catch (Exception ex) {
					ex.printStackTrace();
				}
				dbConnection = new ConnectDB(userName, password, dbURL, dbName);
			}
		}
		return dbConnection;
	}

	public ResultSet runSqlQuery(String sql) throws SQLException {
		Statement s = cn.createStatement();
		ResultSet rs = s.executeQuery(sql);
		return rs;
	}

	public Statement createStatement() throws SQLException {
		return cn.createStatement();
	}

	public int runSqlUpdate(String sql) throws SQLException {
		Statement s = cn.createStatement();
		return s.executeUpdate(sql);
	}

	public void commit() throws SQLException {
		cn.commit();
	}

	public void close() throws SQLException {
		cn.close();
	}

}
